#!/bin/sh

cd `dirname $0`
echo "Running I2P Bundle from $(pwd)..."

# Runs i2pd
_run_i2pd() {
	ulimit -n 4096
	if [ -f i2pd/i2pd ]; then
		i2pd/i2pd --datadir i2pd-data --httpproxy.enabled=1 --sam.enabled=1
	else
		i2pd --datadir i2pd-data --httpproxy.enabled=1 --sam.enabled=1
	fi
}

# Runs XD BitTorrent client
_run_XD() {
	mkdir XD-data
	cd XD-data
	if [ -f ../XD/XD ]; then
		../XD/XD torrents.ini
	else
		XD torrents.ini
	fi
}

# Runs tor
_run_tor() {
	if [ -f tor/tor ]; then
		tor/tor -f tor-data/torrc
	else
		tor -f tor-data/torrc
	fi
}

_killit () {
	# Sends SIGQUIT (-3), waits for 7 seconds then sends SIGKILL (-9)
	pidof $1 && pkill -3 $1 && sleep 7 && pkill -9 $1 || echo "$1 not running, so skipping pkill call"
}

# Run all the i2p stuff, plus tor before running browser
# These will be killed later when browser quits. See "commands after semicolons" comment.
_run_i2pd &
_run_XD &
_run_tor &

# Prepare to run browser
mkdir -p icecat-data
echo "Attempting to run the browser..."
echo "Once it runs you will be able to access:"
echo "- i2pd panel: http://127.0.0.1:7070/"
echo "- XD webui: http://127.0.0.1:1776/"
# Run browser. Commands after semicolons are run after Ctrl+C is pressed or icecat is quit.
icecat/icecat --no-remote --profile "$PWD/icecat-data";
echo "Killing XD, i2pd and tor...";
_killit XD &
_killit i2pd &
_killit tor &
